const express = require('express');
const router = express.Router();

const Users = require('../../../models/product_type');
const Products = require('../../../models/products');

// 注册
router.post('/regist', (req,res) => {
  let model = new Users(req.body);
  var user = req.body.user;
  Users.find({user:user}).exec(function(err,data){
    if(err){
      res.json({
        status: 'n',
        msg:err
      })
    }else{
      if(data.length == 0){
        model.save()
        .then(rev => {
          res.json({
            status: 'y',
            msg: '注册成功',
            info: '保存数据成功'
          })
        })
        .catch(err => {
          res.json({
            status: 'n',
            msg: '注册失败',
            info: err,
          });
        })
      }else{
        res.json({
          status: 'n',
          msg: '用户名已被注册'
        })
      }
    }
  })
});

//  登录
router.post('/login', (req, res) => {
  var user = req.body.user;
  var psw = req.body.psw;
  Users.find({user:user}).exec(function(err,data){
    if(err){
      res.json({
        status: 'n',
        msg: '查找失败',
        info: err,
      })
    }else{
      console.log(data)
      if(data[0].psw !== psw){
        res.json({
          status:'n',
          msg:'登录失败'
        })
      }else{
          res.json({
            status: 'y',
            msg: '登录成功'
          })
      }
    }
  })
});
// 更改密码
router.post('/update',(req,res) => {
 var user = req.body.user;
 var psw = req.body.psw;
 var psw1 = req.body.psw1;
Users.update({user:user},{psw:psw1},function(err,data){
    if(!err){
      res.json({
        status: 'y',
        msg: '修改成功'
      })
    }
})
});
// 提交订单
router.post('/subOrder',(req,res) => {
  let model = new Products(req.body);
  console.log(model)
      model.save()
      .then(rev => {
        res.json({
          status: 'y',
          msg: '保存成功',
          info: '保存数据成功'
        })
      })
      .catch(err => {
        res.json({
          status: 'n',
          msg: '保存失败',
          info: err,
        });
      })
})
router.post('/orderlist',(req,res) => {
  var user = req.body.user;
  Products.find({user:user}).exec(function(err,data){
    if(!err){
      res.json({
        status:'y',
        msg: '查找成功',
        data
      })
    }else{
      res.json({
        status: 'n',
        msg: '查找失败'
      })
    }
  })
})
router.post('/delete/:id',(req,res) => {
  Users.findByIdAndRemove(req.params.id)
    .then(res => {
      res.json({
        status: 'n',
        msg: '删除成功',
        info: '删除数据成功'
      })
    })
    .catch(err => {
      res.json({
        status: 'n',
        msg: '删除数据失败',
        info: err,
      });
    })
});

module.exports = router;
